package com.example.qecode.service;

import com.example.qecode.pojo.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.google.zxing.qrcode.QRCodeWriter;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.swing.filechooser.FileSystemView;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

@Service
public class QECodeServiceImpl implements QECodeService{


    @Override
    public void createQE() throws IOException, WriterException {
        User user1 = new User();
        user1.setAge(200);
        user1.setName("test");
        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(user1);
        this.generateQRCode(s, "qrcode.png", "C:\\Users\\GY\\Desktop\\qecode",  300, 300);
    }


    public void generateQRCode(String text, String fileName,String filePath, int width, int height) throws WriterException, IOException {
        // 创建二维码写入器
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);

        // 创建 BufferedImage
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? Color.BLACK.getRGB() : Color.WHITE.getRGB());
            }
        }
        // 保存为文件
//        File file = new File(fileName);
        File file = new File(filePath + File.separator + fileName);
        ImageIO.write(image, "png", file);
        System.out.println("二维码已生成：" + file.getAbsolutePath());
    }

    @Override
    public String decode() throws IOException, WriterException, ChecksumException, NotFoundException, FormatException {
        // 读取二维码图片
        File file = new File("C:\\Users\\GY\\Desktop\\qecode\\qrcode.png");
        BufferedImage bufferedImage = ImageIO.read(file);

        return this.decodeQRCode(bufferedImage);
    }



    //根据二维码图片解析数据
    public String decodeQRCode(BufferedImage bufferedImage) throws  NotFoundException, ChecksumException, FormatException {
        // 将图片转为 LuminanceSource
        BufferedImageLuminanceSource luminanceSource = new BufferedImageLuminanceSource(bufferedImage);

        // 创建 BinaryBitmap
        BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(luminanceSource));

        // 使用 QRCodeReader 解析二维码
        QRCodeReader qrCodeReader = new QRCodeReader();
        Result result = qrCodeReader.decode(binaryBitmap);

        // 返回二维码内容
        return result.getText();
    }
}
